#define _CRT_RAND_S
#include <stdlib.h>
#include "util.h"
#include <cstdio>
#include <cstring>


#define RAND_MAXS    (6978)

void * util_malloc(size_t n)
{
    return malloc(n);
}

void * util_memset(void *s, int c, size_t n)
{
   return memset(s, c, n); 
}

int  util_memcmp(const void *a, const void *b, size_t sz)
{
   return memcmp(a, b, sz); 
}

void util_free(void *p)
{
    free(p);
}

int util_strcmp(const char *s1, const char *s2)
{
    return strcmp(s1, s2);
}

unsigned int get_rand(void)
{
	unsigned int num;

	errno_t err;

	err = rand_s(&num);
	
	if (err != 0)
	{
		return (unsigned int)-1;
	}
	return num;
}


int gen_array(int a[], int n)
{
	if (a == nullptr || n <= 0)
		return -1;
	for (int i = 0; i < n; i++)
	{
#if 1
        unsigned int t = get_rand(); 
		a[i] = t > RAND_MAXS ? t % n : t;
#else
        a[i] = get_rand();
#endif
	}

	return 0;
}

void destroy_array_mem(void *p)
{
    free(p);
}

int *get_array_mem(int n)
{
    int *a = nullptr;

    a = (int *)malloc(n * sizeof(int));

    if(a == nullptr)
    {
        printf_s("malloc %d memory failed!\r\n", n);
        return a;
    }
    else
        return a;
}

void copy_array(int a[], int b[], int n)
{
    if(a == nullptr || b == nullptr || n <= 1)
        return;

    memcpy(a, b, n * sizeof(int));
}
/* Do not forget to release *a */
void xcopy_array(int **a, int b[], int n)
{
    if(a == nullptr || b == nullptr || n <= 1)
        return;
    if((*a = get_array_mem(n)) != nullptr)
    {
        copy_array(*a, b, n);
    }
}


int cmp_array(int a[], int b[], int n)
{
    if(a == nullptr || b == nullptr || n <= 1)
        return -1;
    for(int i = 0; i < n; i++)
    {
        if(a[i] != b[i])
            return i;

    }
    return 0;
}

void prt_array(int a[], int n)
{
    if(a == nullptr || n <= 1)
        return;
    for(int i = 0; i < n; i++)
    {
        printf_s("%d ", a[i]);
    }
    printf_s("\n");
}

static unsigned int get_rand_next(unsigned int n)
{
    unsigned int r = get_rand();

    if(r < n)
        return r;
    else
        return r % n;
}


void shuffle_array(int a[], int n)
{
   int r, i, t;
   for(i = 0; i < n; i++)
   {
       r = i + get_rand_next(n-i);
       t = a[i];
       a[i] = a[r];
       a[r] = t;
   }
}



